package com.tencent.wuyanzu.whattoeat;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.tencent.wuyanzu.whattoeat.Global.ARGS;
import com.tencent.wuyanzu.whattoeat.net.NetUtil;
import com.tencent.wuyanzu.whattoeat.util.GridViewImageAdapter;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;

public class InitFlavourActivity extends Activity {

    final String TAG = "InitFlavourActivity";
    String[] urls = null;
    JSONArray foodsJsonArr = null;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            int msgWhat = msg.what;
            switch (msgWhat) {
                case 1:
                    String response = msg.getData().getString("result");
                    try {
                        JSONObject receiveJSongOjb = new JSONObject(response);
                        JSONObject foodJsonObj = receiveJSongOjb.getJSONObject("init");
                        foodsJsonArr = foodJsonObj.getJSONArray("food");
                        SharedPreferences msharePreference = getSharedPreferences("whattoeat", Activity.MODE_PRIVATE);
                        SharedPreferences.Editor msharePreferenceEd = msharePreference.edit();
                        ARGS.UID = foodJsonObj.getInt("uid");
                        msharePreferenceEd.putInt("uid", foodJsonObj.getInt("uid"));
                        msharePreferenceEd.commit();
                        urls = new String[foodsJsonArr.length()];
                        for (int i = 0; i < foodsJsonArr.length(); i++) {
                            urls[i] = foodsJsonArr.getJSONObject(i).getString("url");
                        }
                        for (int i = 0; i < foodsJsonArr.length(); i++) {
                            Log.i(TAG, urls[i]);
                        }
                        GridViewImageAdapter gridViewImageAdapter = new GridViewImageAdapter(InitFlavourActivity.this, 0, urls, foodChoseView);
                        foodChoseView.setAdapter(gridViewImageAdapter);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
                default:
                    Log.i(TAG, "unsupport msgWhat");

            }
        }

    };


    GridView foodChoseView;
    Button enterButton;
    final int foodChoseCount = 9;
    //selected picture postion array
    ArrayList<Integer> selectedPositon = new ArrayList<>();
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_init_flavour);
        foodChoseView = (GridView) findViewById(R.id.init_eat_foodGridView);
        foodChoseView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        NetUtil.executeGet("/init", handler, 1);
//        //准备要添加的数据条目
//        List<Map<String, Object>> items = new ArrayList<Map<String,Object>>();
//        for (int i = 0; i < foodChoseCount; i++) {
//            Map<String, Object> item = new HashMap<String, Object>();
//            item.put("imageItem", R.drawable.cai);//添加图像资源的ID
//            item.put("textItem", R.drawable.init_eat_whitechose);
//            items.add(item);
//        }
//        //实例化一个适配器
//        SimpleAdapter adapter = new SimpleAdapter(this,
//                items,
//                R.layout.init_eat_fooditem,
//                new String[]{"imageItem", "textItem"},
//                new int[]{R.id.init_eat_foodImage , R.id.init_eat_foodImage_chose});
//        //为GridView设置适配器
//        foodChoseView.setAdapter(adapter);


        final Bitmap redChooseBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.init_eat_redchose);
        final Bitmap whiteChooseBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.init_eat_whitechose);
        final boolean foodchooseState[] = new boolean[foodChoseCount];
        final StringBuilder selectString = new StringBuilder();
        try {

            boolean isFirst =true;
            for(int i=0;i<foodchooseState.length;i++)
            {
                if(foodchooseState[i])
                {
                    if(isFirst)
                    {
                        isFirst=false;
                    }
                    else
                    {
                        selectString.append(",");
                    }
                    selectString.append(foodsJsonArr.getJSONObject(i).getString("fid"));
                }
            }


        }
        catch ( Exception e)
        {
            e.printStackTrace();
        }


        foodChoseView.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        ImageView chooseImageView = (ImageView) view.findViewById(R.id.init_eat_foodImage_chose);
                        Boolean isChoose = foodchooseState[position];

                        if (isChoose) {
                            chooseImageView.setImageBitmap(whiteChooseBitmap);
                            selectedPositon.add(position);
                        } else {
                            chooseImageView.setImageBitmap(redChooseBitmap);
                        }
                        foodchooseState[position] = !foodchooseState[position];
                    }
                }
        );
        enterButton = (Button) findViewById(R.id.enter_whattoeat_Button);
        enterButton.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpUtils
                        .post()
                        .url(ARGS.HOSTPRE + "//test")
                        .addParams("uid", "" + ARGS.UID)
                        .addParams("selectedFid",selectString.toString())
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {

                            }
                        });
                Intent mainIntent = new Intent(InitFlavourActivity.this, MainActivity.class);
                InitFlavourActivity.this.startActivity(mainIntent);
                InitFlavourActivity.this.finish();
            }
        });


        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "InitFlavour Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.tencent.wuyanzu.whattoeat/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "InitFlavour Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.tencent.wuyanzu.whattoeat/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }
}
